#!/bin/bash
#
# edit wiki use markdown (by @skyblue)
# 
# dependency: xsel(clipboard) markdown(md2html)
#
if test "$#" -ne 1 -o "$1" = "-h" -o "$1" = "--help"
then
	echo "Usage: $0 [*.wiki]"
	exit 1
fi

IN=$1

# temp markdown file
TMPFILE=$(tempfile --suffix=".md")
trap "/bin/rm $TMPFILE" EXIT

if test -f $IN
then 
	sed -n '3,/-->/p' $IN | head -n-1 > $TMPFILE
fi

vim $TMPFILE

# markdown to wiki
cat <<EOF > $IN
<!-- edit by mdwiki(source file http://git.jumbo.ws/shxsun/md2wiki) -->
<!--
$(cat $TMPFILE)
-->
<style>
h1, h2, h3, h4, h5, h6 { font-weight: bold; color: black; }
h1 { color: #000000; font-size: 28px; } 
h2 { border-bottom: 2px solid #CCCCCC; color: #000000; font-size: 24px; }
h3 { border-bottom: 2px solid #CCCCCC; font-size: 18px; }
h4 { font-size: 16px; }
h5 { font-size: 14px; }
h6 { color: #777777; background-color: inherit; font-size: 14px; }
</style>
$(markdown $TMPFILE)
EOF

# copy to clipboard
echo "Copy to clipboard"
xsel --clipboard < $IN
